/*******************************************************************************
 * Copyright (c) 2011 TXT e-solutions SpA
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 *
 * Authors:
 *     Cristoforo Seccia (TXT e-solutions SpA)
 *
 * Contributors:
 *      Domenico Rotondi (TXT e-solutions SpA)
 *******************************************************************************/
package it.txt.access.capability.demo.client.view;

import it.txt.access.capability.demo.client.view.WaitFrame;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.SwingUtilities;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;

/**
 *
 * @author Cristoforo Seccia (TXT e-solutions SpA)
 */
public class WaitFrameController implements PropertyChangeListener {

    private static final Logger logger = Logger.getLogger(WaitFrameController.class.getName());
    private String initApplicationName;
    private WaitFrame waitFrame;
    private Task task;

    public WaitFrameController(String initAppName){
        waitFrame = new WaitFrame();
        initApplicationName = initAppName;
        waitFrame.setApplicationLoadingInfo("Loading " + initApplicationName + "...");
    }

    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            waitFrame.setApplicationLoadingIndeterminate(false);
            waitFrame.setApplicationLoadingPercentage(progress);
            waitFrame.setApplicationLoadingInfo(String.format(
                    "Completed %d%% of task.\n", progress));
        }
    }

    protected class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            Random random = new Random();
            setProgress(0);
            //Initialize progress property.
            setProgress(0);
            //Sleep for at least one second to simulate "startup".
            try {
                Thread.sleep(1000 + random.nextInt(2000));
            } catch (InterruptedException ignore) {
            }
            while (getProgress() < 100) {
                //Sleep for up to two second.
                try {
                    Thread.sleep(random.nextInt(2000));
                } catch (InterruptedException ignore) {
                }
                //Make random progress.
                setProgress(getProgress() + random.nextInt(10));
                setProgress(Math.min(getProgress(), 100));
            }
            return null;
        }

        /*
         * Executed in event dispatch thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            waitFrame.setApplicationLoadingIndeterminate(false);
            waitFrame.setApplicationLoadingPercentage(100);
            waitFrame.setApplicationLoadingInfo(initApplicationName + " Ready.");
        }
    }

    public boolean isApplicationLoadingFrameVisible() {
        return waitFrame.isVisible();
    }

    public void displayApplicationLoadingFrame() {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension ssize = toolkit.getScreenSize();
        int x = (int) (ssize.getWidth() - waitFrame.getWidth()) / 2;
        int y = (int) (ssize.getHeight() - waitFrame.getHeight()) / 2;
        waitFrame.setLocation(x, y);
        waitFrame.setApplicationLoadingIndeterminate(true);
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                waitFrame.setVisible(true);
            }
        });
    }

    public void closeApplicationLoadingFrame() {
        if(!task.isDone()){
            logger.log(Level.INFO, "Task Not Done.");
            task.done();
        }
        logger.log(Level.INFO, "Task Done.");
        waitFrame.setVisible(false);
        waitFrame.dispose();
    }
}
